package com.heima.user.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.directory.shared.kerberos.codec.kdcReqBody.actions.StoreKdcOptions;
import org.bouncycastle.crypto.Digest;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * app登录功能
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.正常登录
        if(StringUtils.isNotBlank(loginDto.getPhone()) && StringUtils.isNotBlank(loginDto.getPassword())){
            //2.根据手机号查询用户信息
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,loginDto.getPhone());
            ApUser dbUser = this.getOne(wrapper);
            if(dbUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"没有用户信息");
            }


            //3.对比密码
            String password = loginDto.getPassword();
            String salt = dbUser.getSalt();
            String md5DigestAsHex = DigestUtils.md5DigestAsHex((password + salt).getBytes()); //md5加盐加密
            if(!md5DigestAsHex.equals(dbUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //4.登录成功，返回jwt
            String token = AppJwtUtil.getToken(dbUser.getId().longValue());

            //5.对照返回值格式，保证格式一致
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            dbUser.setPassword("");
            dbUser.setSalt("");
            map.put("user",dbUser);
            return ResponseResult.okResult(map);


        }
        //2.游客登录，不用返回用户信息，只需返回token
        else {
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }

    }
}























